/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package io.renren.common.tool.redis;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import io.renren.common.tool.security.enums.UserKillEnum;
import io.renren.common.tool.security.user.UserDetail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 用户Redis
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0
 */
@Component
public class UserDetailRedis {
    @Autowired
    private RedisUtils redisUtils;

    public void set(UserDetail user, long expire){
        if(user == null){
            return ;
        }
        String key = RedisKeys.getSecurityUserKey(user.getId());
        //bean to map
        user.setKill(UserKillEnum.NO.value());
        Map<String, Object> map = BeanUtil.beanToMap(user, false, true);
        redisUtils.hMSet(key, map, expire);

        //用户登录时，清空菜单导航、权限标识
        redisUtils.delete(RedisKeys.getUserMenuNavKey(user.getId()));
        redisUtils.delete(RedisKeys.getUserPermissionsKey(user.getId()));
    }

    public UserDetail get(String id){
        String key = RedisKeys.getSecurityUserKey(id);

        Map<String, Object> map = redisUtils.hGetAll(key);
        if(MapUtil.isEmpty(map)){
            return null;
        }

        //map to bean
        UserDetail user = BeanUtil.mapToBean(map, UserDetail.class, true);

        return user;
    }

    /**
     * 用户退出
     * @param id  用户ID
     */
    public void logout(String id){
        String key = RedisKeys.getSecurityUserKey(id);
        redisUtils.hSet(key, "kill", UserKillEnum.YES.value());
    }
}